﻿using SHDM.Cache;
using SHDM.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace SHDM.Web.Infrastructure
{
    public class WebActionFilterAttribute : ActionFilterAttribute, IActionFilter
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {

            if (filterContext.RouteData.DataTokens.Keys.Contains("area"))
            {
                string areaName = filterContext.RouteData.DataTokens["area"].ToString();
                if (areaName == "HelpPage")
                {
                    base.OnActionExecuting(filterContext);
                    return;
                }
            }
            var request = filterContext.RequestContext.HttpContext.Request;
            if (filterContext.RequestContext.HttpContext.Request.RawUrl.ToUpper() != "/LOGIN/")
            {
                if (request.Params.AllKeys.Contains("token"))
                {
                    var token =  request["token"];
                    var accountInfo = Cacher.Instance.Get<AccountInfo>($"{Cacher.KeySpace.UserToken}.{token}");
                    if (accountInfo != null && accountInfo.ID > 0)
                    {
                        filterContext.HttpContext.User = new HPrincipal(new HIdentity(accountInfo));
                        base.OnActionExecuting(filterContext);
                        return;
                    }
                }
                filterContext.RequestContext.HttpContext.Response.Redirect("/Login/");
                return;
            }
            base.OnActionExecuting(filterContext);
        }
    }
}